package com.shushan.pages.newtype;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.net.bean.NetRetBean;
import com.android.net.core.common.RequestType;
import com.android.net.helper.NetHelper;
import com.android.net.listener.common.CallbackCode;
import com.android.net.url.UrlParse;
import com.shushan.base.BaseExerciseHeaderActivity;
import com.shushan.base.Constants;
import com.shushan.exercise.ContinueExerciseHelp;
import com.shushan.mixedexam.MixedExamActivity;
import com.shushan.mixedexam.englishwords.EnglishWordsStudyActivity;
import com.shushan.network.UrlCommParse;
import com.shushan.network.UrlConst;
import com.shushan.network.listener.NetSingleCommListener;
import com.shushan.network.listener.NetStrCommListener;
import com.shushan.pages.StudyProgressSetActivity;
import com.shushan.pages.bean.SubjectSyncExerciseBean;
import com.shushan.pages.newtype.adapter.EnglishWordsRecyclerAdapter;
import com.shushan.pages.newtype.bean.EnglishWordsEntryItemBean;
import com.shushan.pages.newtype.bean.EnglishWordsExerciseEntryBean;
import com.shushan.shushanbao.BabyApplication;
import com.shushan.shushanbao.BuildConfig;
import com.shushan.shushanbao.R;
import com.shushan.util.DialogUtil;
import com.shushan.util.DownloadUtil;
import com.shushan.util.ImageUtils;
import com.shushan.util.Session;
import com.shushan.util.ToolUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName: EnglishWordsExerciseActivity
 * @Desciption: //英语单词练习入口界面
 * @author: zhangshihao
 * @date: 2018-06-27
 */
public class EnglishWordsExerciseActivity extends BaseExerciseHeaderActivity implements View.OnClickListener,
        EnglishWordsRecyclerAdapter.OnItemClickListener{

    private static final String TAG = EnglishWordsExerciseActivity.class.getSimpleName();

    private RecyclerView recyclerView;
    private ImageView ivBook;
    private TextView tvProgressNow;
    private Button btnStartStudy,btnStartExercise;
    private LinearLayout llSetProgress;
    private LinearLayout llPreLesson,llNextLesson;
    private TextView noWordsText;
    private Dialog continueDialog;

    private SubjectSyncExerciseBean englishExerciseBean;
    private List<EnglishWordsEntryItemBean> entryItemBeans;
    private int outline_detail_id = 0;
    private int progress_lock;
    private BabyApplication shuShanApplication = BabyApplication.getInstance();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_english_words_exercise);

        setTitle("单词练习");

        initView();
    }

    private void initView(){
        noWordsText = findViewById(R.id.english_words_no_tv);
        recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL));
        ivBook = findViewById(R.id.iv_english_book);
        tvProgressNow = findViewById(R.id.tv_progress_now_english);
        btnStartStudy = findViewById(R.id.btn_start_study);
        btnStartStudy.setOnClickListener(this);
        btnStartExercise = findViewById(R.id.btn_start_exercise);
        btnStartExercise.setOnClickListener(this);
        llSetProgress = findViewById(R.id.ll_set_progress_english);
        llSetProgress.setOnClickListener(this);
        llPreLesson = findViewById(R.id.ll_pre_lesson_english);
        llPreLesson.setOnClickListener(this);
        llNextLesson = findViewById(R.id.ll_next_lesson_english);
        llNextLesson.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getData();
    }

    @Override
    protected void onStop() {
        super.onStop();

        if(continueDialog != null){
            continueDialog.dismiss();
        }
    }

    private void getData(){
        int childId = shuShanApplication.getCurrentChildId();
        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.MUTIPLE_TYPES_LIST);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("child_id",childId)
                .putValue("practice_type", Constants.TYPE_ENGLISH_WORDS_EXERCISE);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetSingleCommListener<EnglishWordsExerciseEntryBean>() {

                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(EnglishWordsExerciseEntryBean englishWordsExerciseEntryBean) {
                        if(englishWordsExerciseEntryBean == null){
                            return;
                        }

                        int paperId = englishWordsExerciseEntryBean.paper_id;
                        if(paperId > 0){
                            continueDialog = ContinueExerciseHelp.showContinueDialog(EnglishWordsExerciseActivity.this,Constants.TYPE_ENGLISH_WORDS_EXERCISE,paperId);
                        }

                        englishExerciseBean = englishWordsExerciseEntryBean.englishExerciseBean;
                        progress_lock = englishWordsExerciseEntryBean.progress_lock;
                        outline_detail_id = englishExerciseBean.outline_detail_id;
                        entryItemBeans = englishWordsExerciseEntryBean.getEntryItemBeans();

                        if(ToolUtils.isListEmpty(entryItemBeans)){
                            noWordsText.setVisibility(View.VISIBLE);
                        }else {
                            noWordsText.setVisibility(View.GONE);
                        }

                        setData(englishWordsExerciseEntryBean);
                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {
                        showNetError(netRetBean);
                    }
                });
    }

    private void setData(EnglishWordsExerciseEntryBean englishWordsExerciseEntryBean){
        if(englishExerciseBean == null || englishWordsExerciseEntryBean == null){
            showToast("setData : 数据bean为空");
            return;
        }
        setHeaderText(shuShanApplication.getCurrentChildBean(),englishWordsExerciseEntryBean.score,englishWordsExerciseEntryBean.time);

        ImageUtils.loadWXImageView(this,englishExerciseBean.outline_cover,ivBook);
        tvProgressNow.setText("当前进度："+englishExerciseBean.outline_detail_name);

        EnglishWordsRecyclerAdapter recyclerAdapter = new EnglishWordsRecyclerAdapter(entryItemBeans);
        recyclerAdapter.setOnItemClickListener(this);
        recyclerView.setAdapter(recyclerAdapter);

        downloadData();
    }

    private void downloadData(){
        if(ToolUtils.isListEmpty(entryItemBeans)){
            Log.d(TAG,"downloadData : entryItemBeans为空");
            return;
        }
        List<String[]> downloadInfos = new ArrayList<>();
        for(int i=0;i<entryItemBeans.size();i++){
            EnglishWordsEntryItemBean itemBean = entryItemBeans.get(i);
            if(TextUtils.isEmpty(itemBean.voice)){
                continue;
            }
            String[] strs = {DownloadUtil.getEnglishWordsStudyAudioPath(outline_detail_id,itemBean.id),BuildConfig.wxUpImgBaseUrl+itemBean.voice};
            downloadInfos.add(strs);
        }
        DownloadUtil.getInstance().createEnglishWordsDownloadDir();
        DownloadUtil.getInstance().downloadData(this,downloadInfos);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_start_study://开始学习
                if(ToolUtils.isListEmpty(entryItemBeans)){
                    showToast("本课没有新的单词");
                    break;
                }

                if(!(shuShanApplication.isSectVip(Constants.TYPE_ENGLISH_WORDS_EXERCISE)
                        || englishExerciseBean == null
                        || englishExerciseBean.state == 0)){
                    DialogUtil.showNoVipDialog(this,Constants.TYPE_ENGLISH_WORDS_EXERCISE);
                    return;
                }

                Session.getSession().put("entryItemBeans",entryItemBeans);

                Intent intent = new Intent(EnglishWordsExerciseActivity.this, EnglishWordsStudyActivity.class);
                intent.putExtra("outline_detail_id",outline_detail_id);
                intent.putExtra("position",0);
                startActivityAllow(intent);
                break;
            case R.id.btn_start_exercise://开始练习
                if(ToolUtils.isListEmpty(entryItemBeans)){
                    showToast("本课没有新的单词");
                    break;
                }

                if(!(shuShanApplication.isSectVip(Constants.TYPE_ENGLISH_WORDS_EXERCISE)
                        || englishExerciseBean == null
                        || englishExerciseBean.state == 0)){
                    DialogUtil.showNoVipDialog(this,Constants.TYPE_ENGLISH_WORDS_EXERCISE);
                    return;
                }

                Intent intent1 = new Intent(EnglishWordsExerciseActivity.this, MixedExamActivity.class);
                intent1.putExtra("examType",Constants.TYPE_ENGLISH_WORDS_EXERCISE);
                startActivityForResultAllow(intent1);
                break;
            case R.id.ll_set_progress_english://设置进度
                gotoSetProgress();
                break;
            case R.id.ll_pre_lesson_english://上一课
                setSubjectProgress(1);
                break;
            case R.id.ll_next_lesson_english://下一课
                setSubjectProgress(2);
                break;
        }
    }

    /**
     * 设置下一课和上一课
     * @param type 1:上一课；2下一课
     */
    private void setSubjectProgress(int type) {
        if(progress_lock == 0){
            showToast("学生不可以调节进度");
            return;
        }

        int childId = shuShanApplication.getCurrentChildId();

        int outline_id = 0;
        int outline_detail_id = 0;
        if(englishExerciseBean != null){
            outline_id = englishExerciseBean.outline_id;
            outline_detail_id = englishExerciseBean.outline_detail_id;
        }

        UrlParse urlParse = new UrlCommParse(this, UrlConst.BASE_URL).appendRegion(UrlConst.SET_NEXT_PRE_PROGRESS);
        UrlParse paramParse = new UrlCommParse(this)
                .putValue("subject_id", Constants.SUBJECT_ENGLISH_ID + "")
                .putValue("child_id", childId)
                .putValue("type", type + "")
                .putValue("outline_id", outline_id + "")
                .putValue("outline_detail_id", outline_detail_id + "")
                .putValue("practice_type",Constants.TYPE_ENGLISH_WORDS_EXERCISE);
        showWaitDialog();
        NetHelper.create()
                .url(urlParse.toStringOnlyHeader())
                .param(paramParse.toStringOnlyParam())
                .request(RequestType.REQUEST_TYPE_POST, new NetStrCommListener() {
                    @Override
                    protected void onCommon() {
                        dismissWaitDialog();
                    }

                    @Override
                    protected void onSuccess(String data) {
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(data);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        if(jsonObject != null){
                            int outlineDetailId = jsonObject.optInt("outline_detail_id",0);
                            String outlineName = jsonObject.optString("outline_name","");
                            setSwitchProgress(outlineDetailId,outlineName);
                            getData();
                        }

                    }

                    @Override
                    protected void onError(CallbackCode errorCode, NetRetBean netRetBean) {

                        showNetError(netRetBean);
                    }
                });
    }


    private void setSwitchProgress(int outlineDetailId, String outlineName){
        if(TextUtils.isEmpty(outlineName) || outlineDetailId <= 0){
            return;
        }

        tvProgressNow.setText("当前进度：" + outlineName);
        englishExerciseBean.outline_detail_id = outlineDetailId;
        englishExerciseBean.outline_detail_name = outlineName;
    }


    private void gotoSetProgress() {
        if(progress_lock == 0){
            showToast("学生不可以调节进度");
            return;
        }

        if(englishExerciseBean != null){
            Intent intent = new Intent(this,StudyProgressSetActivity.class);
            intent.putExtra("subjectId",Constants.SUBJECT_ENGLISH_ID);
            intent.putExtra("outlineId",englishExerciseBean.outline_id);
            intent.putExtra("outlineDetailId",englishExerciseBean.outline_detail_id);
            intent.putExtra("practiceType",Constants.TYPE_ENGLISH_WORDS_EXERCISE);
            startActivityForResultAllow(intent);
        }
    }

    @Override
    public void onItemClick(int position) {
        if(!(shuShanApplication.isSectVip(Constants.TYPE_ENGLISH_WORDS_EXERCISE)
                || englishExerciseBean == null
                || englishExerciseBean.state == 0)){
            DialogUtil.showNoVipDialog(this,Constants.TYPE_ENGLISH_WORDS_EXERCISE);
            return;
        }

        Session.getSession().put("entryItemBeans",entryItemBeans);

        Intent intent = new Intent(EnglishWordsExerciseActivity.this, EnglishWordsStudyActivity.class);
        intent.putExtra("outline_detail_id",outline_detail_id);
        intent.putExtra("position",position);
        startActivityAllow(intent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(resultCode == 200){
            onBackAction();
        }
    }
}
